package cn.example.demo.modules.house.service.impl;

import cn.example.demo.modules.house.dto.RegionDto;
import cn.example.demo.modules.house.entity.Region;
import cn.example.demo.modules.house.mapper.RegionMapper;
import cn.example.demo.modules.house.service.IRegionService;
import cn.example.demo.common.model.service.ServiceResult;
import cn.example.demo.common.model.tree.factory.DefaultTreeBuildFactory;
import cn.example.demo.common.retrieval.PageBean;
import cn.example.demo.common.secure.context.LoginUserApi;
import cn.example.demo.common.tools.QueryServiceUtils;
import cn.example.demo.common.tools.obj.reflect.EntityUtils;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 描述：【地区】接口实现类
 */

@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {
    @Autowired
    private LoginUserApi loginUserApi;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult insertRegion(RegionDto regionDto) {
        Region entity = EntityUtils.entityConvert(regionDto, new Region(), false);

        if (StrUtil.isBlank(regionDto.getParentId())) {
            entity.setParentId(DefaultTreeBuildFactory.ROOT_NODE.toString());
        }

        if (this.save(entity)) {
            return ServiceResult.isSuccess(StrUtil.format("【地区，ID:{}】创建成功!", entity.getId()), entity);
        }

        return ServiceResult.isInternalError("【地区】创建失败，未知错误！");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult updateRegion(RegionDto regionDto) {
        Region entity = this.getById(regionDto.getId());
        if (entity == null) {
            return ServiceResult.isNotFound(StrUtil.format("【地区】信息更新失败：记录不存在！ID:{}", regionDto.getId()));
        }

        entity = EntityUtils.entityConvert(regionDto, entity, true);

        if (StrUtil.isBlank(regionDto.getParentId())) {
            entity.setParentId(DefaultTreeBuildFactory.ROOT_NODE.toString());
        }

        if (this.updateById(entity)) {
            return ServiceResult.isSuccess(StrUtil.format("【地区，ID:{}】信息更新成功!", entity.getId()), null);
        }

        return ServiceResult.isNotModified("未知错误，【地区】信息修改失败！");
    }

    @Override
    public PageBean queryRegion(RegionDto regionDto) {
        Page pageResult = PageHelper.startPage(regionDto.getPageNum(), regionDto.getPageSize())
                .doSelectPage(() -> this.list(getQueryWrapper(regionDto)));

        return QueryServiceUtils.encapsulatePageBean(new PageBean<>(), pageResult);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult deleteRegion(RegionDto regionDto) {
        int rows = this.baseMapper.deleteBatchIds(regionDto.getIds());
        if (rows > 0) {
            // 级联删除子级数据
            LambdaQueryWrapper<Region> wrapper = Wrappers.lambdaQuery();
            wrapper.in(Region::getParentId, regionDto.getIds());
            this.remove(wrapper);

            return ServiceResult.isSuccess(StrUtil.format("操作成功，已批量删除【地区】共 {} 条记录！", rows), rows);
        }

        return ServiceResult.isNotModified("删除【地区】失败，请稍后重试！");
    }

    @Override
    public Region findRegionById(String id) {
        return this.getById(id);
    }

    @Override
    public List<Map<String, Object>> queryRegionAsDict(RegionDto regionDto) {
        return this.baseMapper.selectAsDictList(getQueryWrapper(regionDto));
    }

    @Override
    public ServiceResult queryRegionAsTree(RegionDto regionDto) {
        List<Region> result = this.list(getQueryWrapper(regionDto));

        if (result.isEmpty()) {
            return ServiceResult.isNotFound("没有【地区】数据！");
        }

        // 列表转树结构
        return ServiceResult.isSuccess(new DefaultTreeBuildFactory<Region>().doTreeBuild(result));
    }

    /**
     * 查询条件
     *
     * @param regionDto
     * @return
     */

    protected LambdaQueryWrapper getQueryWrapper(RegionDto regionDto) {
        LambdaQueryWrapper<Region> wrapper = Wrappers.lambdaQuery();

        wrapper
                .like(StrUtil.isNotBlank(regionDto.getId()), Region::getId, regionDto.getId())

                .like(StrUtil.isNotBlank(regionDto.getParentId()), Region::getParentId, regionDto.getParentId())

                .like(StrUtil.isNotBlank(regionDto.getName()), Region::getName, regionDto.getName())

                .like(StrUtil.isNotBlank(regionDto.getRemark()), Region::getRemark, regionDto.getRemark())
                .like(StrUtil.isNotBlank(regionDto.getIsHighRisk()), Region::getIsHighRisk, regionDto.getIsHighRisk())
        ;

        return wrapper;
    }
}
